package com.fablesoft.projectdatacollect.ui;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.bean.CampaignBean;
import com.fablesoft.projectdatacollect.bean.CampaignListResponse;
import com.fablesoft.projectdatacollect.bean.CampaignSizeResponse;
import com.fablesoft.projectdatacollect.dapter.SafeCampaignAdapter;
import com.fablesoft.projectdatacollect.http.HttpListener;
import com.fablesoft.projectdatacollect.http.HttpThread;
import com.fablesoft.projectdatacollect.util.CommonUtils;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.view.MyRefreshListView;
import com.fablesoft.projectdatacollect.view.MyRefreshListView.RefreshListViewListener;
import com.fablesoft.projectdatacollect.view.SpinnerPopWindow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SafeCampaignNewActivity extends BaseRequestActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private List<CampaignBean> campaignListInProcess = new ArrayList<CampaignBean>();
    private List<CampaignBean> campaignListSubmit = new ArrayList<CampaignBean>();
    private MyRefreshListView campaignInprocessListView;
    private MyRefreshListView campaignSubmitedListView;
    private View noDataLayout;
    private View noDataTip;
    private View connectionFailedTip;
    private int pageInprocess = 1;
    private int pageSubmited = 1;
    private int pagesize = 10;
    private static final int REFRESH_INFO_REQUEST_CODE = 101;
    private static final int LOAD_INFO_REQUEST_CODE = 103;
    private static final int DATA_SIZE_CODE = 104;
    private static final int DATA_INPROCESS_CODE = 105;
    private static final int DATA_SUBMITED_CODE = 106;
    public static final int UPDATE_LIST_CODE = 201;
    private View loadingLayout;
    private View loadingProgressbar;
    private View addView;

    private RadioGroup rgTag;
    private RadioButton rbInProcess;
    private RadioButton rbSubmit;
    private int currentPosition = 0;// 0:进行中; 1:已提交

    private SafeCampaignAdapter mInprocessAdapter;
    private SafeCampaignAdapter mSubmitedAdapter;

    private SpinnerPopWindow mSpinerPopWindow;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_safe_new_campaign);
        mInprocessAdapter = new SafeCampaignAdapter(this, campaignListInProcess, listener);
        mSubmitedAdapter = new SafeCampaignAdapter(this, campaignListSubmit, listener);
        initView();
        initDataSize();
        initInprocessData();
    }

    private void initView() {
        campaignInprocessListView = (MyRefreshListView) findViewById(R.id.campaign_inprocess_list);
        campaignSubmitedListView = (MyRefreshListView) findViewById(R.id.campaign_submited_list);
        noDataLayout = findViewById(R.id.no_data_reload_layout);
        noDataTip = findViewById(R.id.no_data_tip);
        connectionFailedTip = findViewById(R.id.connection_failed_tip);
        loadingLayout = findViewById(R.id.loading_layout);
        loadingProgressbar = findViewById(R.id.loading_progressbar);

        addView = findViewById(R.id.ll_add);
        addView.setOnClickListener(this);
        mSpinerPopWindow = new SpinnerPopWindow(this, getResources().getStringArray(R.array.campaigntype),
                itemClickListener);
        mSpinerPopWindow.setOnDismissListener(dismissListener);

        View back = findViewById(R.id.back);
        View reloadBtn = findViewById(R.id.reload_btn);
        back.setOnClickListener(mOnClickListener);
        reloadBtn.setOnClickListener(mOnClickListener);
        campaignInprocessListView.setAdapter(mInprocessAdapter);
        campaignInprocessListView.setRefreshListViewListener(inprocessListener);
        campaignInprocessListView.setPullLoadEnable(false);
        campaignSubmitedListView.setAdapter(mSubmitedAdapter);
        campaignSubmitedListView.setRefreshListViewListener(inprocessListener);
        campaignSubmitedListView.setPullLoadEnable(false);
        campaignSubmitedListView.setVisibility(View.GONE);

        rgTag = (RadioGroup) findViewById(R.id.rg_tab);
        rbInProcess = (RadioButton) findViewById(R.id.rb_in_process);
        rbSubmit = (RadioButton) findViewById(R.id.rb_submit);
        rgTag.setOnCheckedChangeListener(this);
        currentPosition = 0;
        changeElevation();
    }

    private void initInprocessData() {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        params.put("size", pagesize);
        params.put("page", pageInprocess);
        map.put("status", CommonUtils.STATUS_IN_PROCESS);
        params.put("mapParams", map);
        showLoading();
        HttpThread httpThread = new HttpThread(Config.CAMPAIGN_LIST_NEW_URL,
                new HttpListener() {
                    @Override
                    public void onRequestFinish(BaseResponse response) {
                        Message msg = mHandler.obtainMessage();
                        msg.obj = response;
                        msg.what = DATA_INPROCESS_CODE;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onNotLogin(BaseResponse response) {
                    }
                }, params, CampaignListResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(httpThread);
    }

    private void initSubmitedData() {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        params.put("size", pagesize);
        params.put("page", pageSubmited);
        map.put("status", CommonUtils.STATUS_SUBMITED);
        params.put("mapParams", map);
        showLoading();
        HttpThread httpThread = new HttpThread(Config.CAMPAIGN_LIST_NEW_URL,
                new HttpListener() {
                    @Override
                    public void onRequestFinish(BaseResponse response) {
                        Message msg = mHandler.obtainMessage();
                        msg.obj = response;
                        msg.what = DATA_SUBMITED_CODE;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onNotLogin(BaseResponse response) {
                    }
                }, params, CampaignListResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(httpThread);
    }

    private void initDataSize() {
        Map<String, Object> mapParams = new HashMap<String, Object>();
        HttpThread httpThread = new HttpThread(Config.CAMPAIGN_LIST_SIZE_URL,
                new HttpListener() {
                    @Override
                    public void onRequestFinish(BaseResponse response) {
                        Message msg = mHandler.obtainMessage();
                        msg.obj = response;
                        msg.what = DATA_SIZE_CODE;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onNotLogin(BaseResponse response) {
                    }
                }, mapParams, CampaignSizeResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(httpThread);
    }


    private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.reload_btn:
                    if (currentPosition == 0) {
                        initInprocessData();
                    } else {
                        initSubmitedData();
                    }
                    break;
                case R.id.back:
                    finish();
                    break;
            }
        }
    };

    private void showLoading() {
        if (loadingProgressbar != null) {
            Animation loadAnimation = AnimationUtils.loadAnimation(SafeCampaignNewActivity.this,
                    R.anim.loading);
            loadingProgressbar.startAnimation(loadAnimation);
        }
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
    }

    private void dismissLoading() {
        if (loadingProgressbar != null) {
            loadingProgressbar.clearAnimation();
        }
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH_INFO_REQUEST_CODE:
                    updateRefreshData(msg.obj);
                    initDataSize();
                    break;
                case LOAD_INFO_REQUEST_CODE:
                    updateLoadData(msg.obj);
                    break;
                case DATA_INPROCESS_CODE:
                    updateData(msg.obj, DATA_INPROCESS_CODE);
                    break;
                case DATA_SUBMITED_CODE:
                    updateData(msg.obj, DATA_SUBMITED_CODE);
                    break;
                case DATA_SIZE_CODE:
                    setTagNumber((CampaignSizeResponse) msg.obj);
                    break;
            }
        }

        ;
    };

    private void showNoDataTip() {
        noDataTip.setVisibility(View.VISIBLE);
        connectionFailedTip.setVisibility(View.GONE);
        noDataLayout.setVisibility(View.VISIBLE);
        if (currentPosition == 0) {
            campaignInprocessListView.setVisibility(View.GONE);
        } else {
            campaignSubmitedListView.setVisibility(View.GONE);
        }
    }

    private void showconnectionFailedTip() {
        noDataTip.setVisibility(View.GONE);
        connectionFailedTip.setVisibility(View.VISIBLE);
        noDataLayout.setVisibility(View.VISIBLE);
        if (currentPosition == 0) {
            campaignInprocessListView.setVisibility(View.GONE);
        } else {
            campaignSubmitedListView.setVisibility(View.GONE);
        }
    }

    private void loginExpire() {
        dismissLoading();
        noDataTip.setVisibility(View.GONE);
        connectionFailedTip.setVisibility(View.GONE);
        noDataLayout.setVisibility(View.VISIBLE);
        if (currentPosition == 0) {
            campaignInprocessListView.setVisibility(View.GONE);
        } else {
            campaignSubmitedListView.setVisibility(View.GONE);
        }
    }

    private void updateData(Object data, int flag) {
        if (data == null) {
            Toast.makeText(SafeCampaignNewActivity.this, R.string.request_error, Toast.LENGTH_SHORT)
                    .show();
            showconnectionFailedTip();
        } else {
            CampaignListResponse newsListResponse = (CampaignListResponse) data;
            if (newsListResponse.getRows() != null) {
                if (currentPosition == 0 && campaignInprocessListView == null) {
                    return;
                }

                if (currentPosition == 1 && campaignSubmitedListView == null) {
                    return;
                }
                if (newsListResponse.getRows().size() == 0) {
                    showNoDataTip();
                } else if (currentPosition == 0) {
                    campaignListInProcess.clear();
                    campaignListInProcess.addAll(newsListResponse.getRows());
                    mInprocessAdapter.notifyDataSetChanged();
                    noDataLayout.setVisibility(View.GONE);
                    campaignInprocessListView.setVisibility(View.VISIBLE);
                    campaignSubmitedListView.setVisibility(View.GONE);
                } else {
                    campaignListSubmit.clear();
                    campaignListSubmit.addAll(newsListResponse.getRows());
                    mSubmitedAdapter.notifyDataSetChanged();
                    noDataLayout.setVisibility(View.GONE);
                    campaignSubmitedListView.setVisibility(View.VISIBLE);
                    campaignInprocessListView.setVisibility(View.GONE);
                }
            } else {
                showNoDataTip();
            }
        }
        dismissLoading();
    }

    private void updateLoadData(Object data) {
        if (data == null) {
            Toast.makeText(SafeCampaignNewActivity.this, R.string.request_error, Toast.LENGTH_SHORT)
                    .show();
        } else {
            CampaignListResponse newsListResponse = (CampaignListResponse) data;
            if (newsListResponse.getRows() != null) {
                if (newsListResponse.getRows().size() == 0) {
                    if (currentPosition == 0) {
                        campaignInprocessListView.setNoDataLoad();
                    } else {
                        campaignSubmitedListView.setNoDataLoad();
                    }
                } else {
                    if (newsListResponse.getRows().size() == pagesize) {
                        if (currentPosition == 0) {
                            campaignInprocessListView.setPullLoadEnable(true);
                        } else {
                            campaignSubmitedListView.setPullLoadEnable(true);
                        }
                    }
                    if (currentPosition == 0) {
                        campaignListInProcess.addAll(newsListResponse.getRows());
                        mInprocessAdapter.notifyDataSetChanged();
                        campaignInprocessListView.setVisibility(View.VISIBLE);
                    } else {
                        campaignListSubmit.addAll(newsListResponse.getRows());
                        mSubmitedAdapter.notifyDataSetChanged();
                        campaignSubmitedListView.setVisibility(View.VISIBLE);
                    }
                    noDataLayout.setVisibility(View.GONE);
                }
            } else {
                if (currentPosition == 0) {
                    campaignInprocessListView.setNoDataLoad();
                } else {
                    campaignSubmitedListView.setNoDataLoad();
                }
            }
        }
        if (currentPosition == 0) {
            campaignInprocessListView.stopLoadMore();
        } else {
            campaignSubmitedListView.stopLoadMore();
        }
    }

    private void updateRefreshData(Object data) {
        if (data == null) {
            Toast.makeText(SafeCampaignNewActivity.this, R.string.request_error, Toast.LENGTH_SHORT)
                    .show();
        } else {
            CampaignListResponse newsListResponse = (CampaignListResponse) data;
            if (newsListResponse.getRows() != null && newsListResponse.getRows().size() != 0) {
                if (currentPosition == 0) {
                    campaignListInProcess.clear();
                    campaignListInProcess.addAll(newsListResponse.getRows());
                    mInprocessAdapter.notifyDataSetChanged();
                } else {
                    campaignListSubmit.clear();
                    campaignListSubmit.addAll(newsListResponse.getRows());
                    mSubmitedAdapter.notifyDataSetChanged();
                }
            }
        }
        if (currentPosition == 0) {
            campaignInprocessListView.stopRefresh();
        } else {
            campaignSubmitedListView.stopRefresh();
        }
    }

    @Override
    public void onNotLogin(BaseResponse response) {
        loginExpire();
        super.onNotLogin(response);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == UPDATE_LIST_CODE) {
            initView();
            initDataSize();
            initInprocessData();
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.rb_in_process:
                Log.d("sglei-tag", "onCheckedChanged test_rb0");
                currentPosition = 0;
                changeElevation();
                campaignInprocessListView.setVisibility(View.VISIBLE);
                campaignInprocessListView.setRefreshListViewListener(inprocessListener);
                campaignSubmitedListView.setRefreshListViewListener(null);
                campaignSubmitedListView.setVisibility(View.GONE);
                initInprocessData();
                break;
            case R.id.rb_submit:
                currentPosition = 1;
                changeElevation();
                campaignInprocessListView.setVisibility(View.GONE);
                campaignInprocessListView.setRefreshListViewListener(null);
                campaignSubmitedListView.setRefreshListViewListener(inprocessListener);
                campaignSubmitedListView.setVisibility(View.VISIBLE);
                initSubmitedData();
                break;
        }
    }

    /**
     * 突出显示控件
     */
    @TargetApi(21)
    private void changeElevation() {
        switch (currentPosition) {
            case 0:
                rbSubmit.setElevation(CommonUtils.TAG_ELEVATION);
                rbInProcess.setElevation(0);
                break;
            case 1:
                rbSubmit.setElevation(0);
                rbInProcess.setElevation(CommonUtils.TAG_ELEVATION);
                break;
        }
    }

    private void setTagNumber(CampaignSizeResponse response) {
        if (response == null) {
            Toast.makeText(SafeCampaignNewActivity.this, R.string.request_error, Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        rbInProcess.setText(getResources().getString(R.string.in_process, response.getData().getInProgressNum()));
        rbSubmit.setText(getResources().getString(R.string.submited, response.getData().getToBeFiledNum()));
    }

    private RefreshListViewListener inprocessListener = new RefreshListViewListener() {
        @Override
        public void onRefresh() {
            Map<String, Object> params = new HashMap<>();
            Map<String, Object> maps = new HashMap<>();
            params.put("size", pagesize);
            params.put("page", pageInprocess);
            if (currentPosition == 0) {
                maps.put("status", CommonUtils.STATUS_IN_PROCESS);
            } else {
                maps.put("status", CommonUtils.STATUS_SUBMITED);
            }
            params.put("mapParams", maps);
            HttpThread httpThread = new HttpThread(Config.CAMPAIGN_LIST_NEW_URL,
                    new HttpListener() {
                        @Override
                        public void onRequestFinish(BaseResponse response) {
                            Message msg = mHandler.obtainMessage();
                            msg.obj = response;
                            msg.what = REFRESH_INFO_REQUEST_CODE;
                            mHandler.sendMessage(msg);
                        }

                        @Override
                        public void onNotLogin(BaseResponse response) {
                            loginExpire();
                            SafeCampaignNewActivity.this.onNotLogin(response);
                        }
                    }, params, CampaignListResponse.class);
            MyApplication.getInstance().getRequestQueue().execute(httpThread);
        }

        @Override
        public void onLoadMore() {
            pageInprocess++;
            Map<String, Object> params = new HashMap<>();
            Map<String, Object> maps = new HashMap<>();
            params.put("size", pagesize);
            params.put("page", pageInprocess);
            if (currentPosition == 0) {
                maps.put("status", CommonUtils.STATUS_IN_PROCESS);
            } else {
                maps.put("status", CommonUtils.STATUS_SUBMITED);
            }
            params.put("mapParams", maps);
            HttpThread httpThread = new HttpThread(Config.CAMPAIGN_LIST_NEW_URL,
                    new HttpListener() {
                        @Override
                        public void onRequestFinish(BaseResponse response) {
                            Message msg = mHandler.obtainMessage();
                            msg.obj = response;
                            msg.what = LOAD_INFO_REQUEST_CODE;
                            mHandler.sendMessage(msg);
                        }

                        @Override
                        public void onNotLogin(BaseResponse response) {
                            loginExpire();
                            SafeCampaignNewActivity.this.onNotLogin(response);
                        }
                    }, params, CampaignListResponse.class);
            MyApplication.getInstance().getRequestQueue().execute(httpThread);
        }
    };


    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(SafeCampaignNewActivity.this, SafeCampaignDetailActivity.class);
            if (v.getTag() != null) {
                int position = (Integer) v.getTag();
                if (currentPosition == 0) {
                    intent.putExtra("activityId", campaignListInProcess.get(position).getId());
                    intent.putExtra("type", campaignListInProcess.get(position).getType());
                } else {
                    intent.putExtra("activityId", campaignListSubmit.get(position).getId());
                    intent.putExtra("type", campaignListSubmit.get(position).getType());
                }
                intent.putExtra("isSubmit", currentPosition == 0 ? false : true);
            }
            startActivityForResult(intent, 0);
        }
    };

    /**
     * 监听popupwindow取消
     */
    private PopupWindow.OnDismissListener dismissListener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.alpha = 1f;
            getWindow().setAttributes(lp);
        }
    };

    /**
     * popupwindow显示的ListView的item点击事件
     */
    private AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            mSpinerPopWindow.dismiss();
            Intent intent = new Intent(SafeCampaignNewActivity.this, SafeCampaignAddActivity.class);
            intent.putExtra("position", position);
            startActivityForResult(intent, 1);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_add:
                mSpinerPopWindow.setWidth(240);
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 0.6f;
                getWindow().setAttributes(lp);
                mSpinerPopWindow.showAsDropDown(addView);
                break;
        }
    }

}
